package com.szh.mysobproject.ui.activity

import androidx.activity.viewModels
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import by.kirich1409.viewbindingdelegate.viewBinding
import com.dylanc.longan.lifecycleOwner
import com.szh.mysobproject.R
import com.szh.mysobproject.action.StatusAction
import com.szh.mysobproject.app.AppActivity
import com.szh.mysobproject.databinding.RichListActivityBinding
import com.szh.mysobproject.ui.adapter.RichListAdapter
import com.szh.mysobproject.util.loadStateListener
import com.szh.mysobproject.viewmodel.UserViewModel
import com.szh.mysobproject.widget.StatusLayout
import kotlinx.coroutines.flow.collectLatest

class RichListActivity : AppActivity(), StatusAction {

    private val mBinding by viewBinding<RichListActivityBinding>()
    private val mUserViewModel by viewModels<UserViewModel>()
    private val mRichListAdapter = RichListAdapter()
    private val loadStateListener = loadStateListener(mRichListAdapter) {
        mBinding.refreshLayout.finishRefresh()
    }

    override fun getLayoutId(): Int = R.layout.rich_list_activity

    override fun initView() {
        mBinding.rvRich.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = mRichListAdapter
        }
    }

    override fun initData() {
        loadRichList()
    }

    private fun loadRichList() {
        lifecycleOwner.lifecycleScope.launchWhenCreated {
            mUserViewModel.getRichList().collectLatest {
                mRichListAdapter.submitData(it)
            }
        }
    }

    override fun initEvent() {
        mBinding.refreshLayout.setOnRefreshListener {
            mRichListAdapter.refresh()
        }
        mRichListAdapter.addLoadStateListener(loadStateListener)

    }

    override fun getStatusLayout(): StatusLayout = mBinding.slRichListLayout

    override fun onDestroy() {
        super.onDestroy()
        mRichListAdapter.removeLoadStateListener(loadStateListener)
    }
}